require 'hmac-sha1'
require 'digest/sha1'
require 'base64'
require 'cgi'

module OAuthHelpers
  def generate_secure_identify mac, timestamp
    # get private key
    private_key = File.read(Rails.root.join('.private_key')).chomp
    # strip `:` in mac address and then reverse it
    mac_clone = mac.dup
    mac_clone.delete!(':').reverse!
    # transfer the first and last half of it
    mac_clone = mac_clone[6..11] + mac_clone[0..5]
    # generate a number array based on timestamp to perform sort
    sort_weight = Digest::MD5.hexdigest(timestamp.to_s)[0..23].chars.each_slice(2).map { |s| s.join.to_i 16 }
    # then sort it
    index = -1
    mac_clone = mac_clone.chars.to_a.sort_by! { |k| sort_weight[index += 1] + index.to_f/100 }.join
    # hmac-sha1
    Base64.urlsafe_encode64(HMAC::SHA1.digest(private_key, mac_clone)).strip
  end

  # Todo: can't get http request object
  def params_with_signature request_url, params = {}
    auth_token = create(:auth_token)
    timestamp = Time.now.to_i
    params_string = params.map { |e| e.map { |k| CGI.escape(k.to_s) }.join('=') }.sort.join('&')
    base_request = params_string.empty? ? request_url : "#{request_url}?#{params_string}"
    request = base_request + auth_token.id.to_s + timestamp.to_s
    salt = Digest::SHA1.hexdigest(request)[0..19]
    signature = Base64.urlsafe_encode64(HMAC::SHA1.digest(auth_token.token, salt)).strip
    result_params = params.merge timestamp: timestamp, client_id: auth_token.id, signature: signature
  end

end